var App = App||{};
$(function(){
	$.ajaxSetup({ dataType: 'json', error: function(data){ App.Error(data); } });
	$('.mainmenu-item-logout').bind('click', function(){
		if (localStorage){
			delete localStorage.u;
			delete localStorage.h;
		}
	});
	$('.mainmenu .icon-password').bind('click', function(){ App.User.changePassword(); });
	
	App.init();
});


App.User = App.User || {};
App.User.changePasswordSubmit = function(content){
	var form = $(content).find('form'), formData = serializeForm(form);
	formData.id = App.User.id;
	$.ajax({ url: 'updateUser', context: this, data: formData })
	.success(function(data){
		if (!data || data.result == 'error'){ App.Error(data); return; }
		this.changePasswordWindow.hide();
		msgbox('Password has been changed');
	});
	
	return false;
};
App.User.changePassword = function(){
	this.changePasswordWindow = new Window({ title: 'Change password', modal: true, disposable: true,
		content: '<form class="change-pass-form"><label><input type="password" name="oldPass" />Old password: </label><label><input type="password" name="password" />New password: </label></form>',		 
		buttons: [{ text: 'Change', cls: 'submit', scope: this, fn: this.changePasswordSubmit }, { text: 'Cancel' }]
	}).show(); 
};



/**
 * Global error handler
 * @param msg	msg object: { result: 'error', type:'', details: 'message details' }
 */
App.Error = function(msg){
	if (msg.status === 0) return false; 									// request interrupted - don't show error
	if (!msg) msgerror('Unknown server error.');
	else if (typeof msg === 'string') msgerror(msg);
	else {
		if (!msg) msgerror('Unknown server error.');
		else {
			if (msg.result == 'auth') msgerror('Access denied.');
			else if (msg.message) msgbox({ type: 'error', text: msg.message, delay: 3 });
			else msgerror('Unknown server error.');
		}
	}
	return false;
};